package com.mh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mh.dao.PayInfoDao;
import com.mh.dto.R;
import com.mh.pojo.PayInfo;
import com.mh.service.PayInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 支付信息表(PayInfo)表服务实现类
 *
 * @author zmh
 * @since 2024-10-01 09:30:27
 */
@Service
public class PayInfoServiceImpl extends ServiceImpl<PayInfoDao, PayInfo> implements PayInfoService {

    @Autowired
    private PayInfoDao payInfoDao;

    /**
     * 分页查询
     *
     * @param page 查询页数
     * @param size 一页显示条数
     * @return ·
     */
    public R<Page<PayInfo>> getAllByPage(int page, int size) {
        Page<PayInfo> payInfoPage = new Page<>(page, size);
        LambdaQueryWrapper<PayInfo> queryWrapper = new LambdaQueryWrapper<>();
        //TODO 查询条件定制
        return R.success(payInfoDao.selectPage(payInfoPage, queryWrapper));
    }

    @Override
    public R<String> testFinish(String openId, String testResult) {
        // 根据用户openID找出未测试完成的记录
        LambdaQueryWrapper<PayInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PayInfo::getOpenId, openId);
        queryWrapper.eq(PayInfo::getTestStatus, 0);
        PayInfo payInfo = payInfoDao.selectOne(queryWrapper);

        if(payInfo == null){
            return R.error("用户支付订单未查到");
        }

        // 更新状态
        payInfo.setFinishTime(LocalDateTime.now());
        payInfo.setTestResult(testResult);
        payInfo.setTestStatus(1);

        // 执行更新
        payInfoDao.updateById(payInfo);
        return R.success("更新成功");
    }

    @Override
    public R<Boolean> checkUserPayStatus(String openId) {
        LambdaQueryWrapper<PayInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PayInfo::getOpenId, openId);
        queryWrapper.eq(PayInfo::getTestStatus, 0);
        PayInfo payInfo = payInfoDao.selectOne(queryWrapper);
        if(payInfo != null){
            return R.success(true);
        }
        return R.error("没有找到支付记录");
    }

    @Override
    public R<List<PayInfo>> getAllByOpenId(String openId) {
        LambdaQueryWrapper<PayInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(PayInfo::getOpenId, openId);
        List<PayInfo> payInfos = payInfoDao.selectList(qw);
        return payInfos != null ? R.success(payInfos) : R.error("没有找到测试/支付记录");
    }
}

